﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Serilog;
using Microsoft.Extensions.Configuration;
using System.IO;
using Serilog.Core;
using Music.Utility.Authorization;
using Microsoft.AspNetCore.Http.Extensions;
using Senparc.CO2NET.Extensions;
using Music.API.Data;

namespace Music.API.Controllers
{
    /// <summary>
    /// 基类，封装了TOKEN、日志相关操作
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseController<T> : Controller
    {

        /// <summary>
        /// _context
        /// </summary>
        protected readonly MusicApiContext _context;
        /// <summary>
        /// 会员ID
        /// </summary>
        public static long GLOBAL_MEMBER_ID { get; set; }
        /// <summary>
        /// Log变量
        /// </summary>
        public Logger log;
        /// <summary>
        /// _httpContextAccessor
        /// </summary>
        private readonly IHttpContextAccessor _httpContextAccessor;

        /// <summary>
        /// 构造基类方法
        /// </summary>
        /// <param name="httpContextAccessor"></param>
        /// <param name="context"></param>
        public BaseController(MusicApiContext context, IHttpContextAccessor httpContextAccessor)
        {
            _context = context;
            _httpContextAccessor = httpContextAccessor;

            //初始化日志
            log = new LoggerConfiguration()
             .ReadFrom.Configuration(new ConfigurationBuilder()
             .SetBasePath(Directory.GetCurrentDirectory())
             .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
             .Build())
             .CreateLogger();

            try
            {
                //swagger
                var authorization = httpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();//前端传递的TOKEN
                if (!string.IsNullOrEmpty(authorization))
                {
                    authorization = authorization.Replace("Bearer ", "");
                    //来自前端请求接口
                    var member_id = JwtToken.ReadJwtToken(authorization);
                    long.TryParse(member_id, out long get_member_id);
                    GLOBAL_MEMBER_ID = get_member_id;
                    log.Information("GLOBAL_MEMBER_ID=" + GLOBAL_MEMBER_ID);
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + " -> authorization");
            }

            try
            {
                //api
                var access_token = httpContextAccessor.HttpContext.Request.Headers["Access-Token"].FirstOrDefault();//前端传递的TOKEN
                if (!string.IsNullOrEmpty(access_token))
                {
                    //来自前端请求接口
                    var member_id = JwtToken.ReadJwtToken(access_token);
                    long.TryParse(member_id, out long get_member_id);
                    GLOBAL_MEMBER_ID = get_member_id;
                    log.Information("GLOBAL_MEMBER_ID=" + GLOBAL_MEMBER_ID);
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + " -> authorization");
            }

        }

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="type"></param>
        ///// <param name="log_content"></param>
        ///// <param name="log_code"></param>
        ///// <returns></returns>
        //[HttpGet]
        //public IActionResult AddLogs(int type, string log_content, string log_code)
        //{
        //    try
        //    {
        //        string page_url = HttpContext.Request.GetDisplayUrl();
        //        string referrer_url = HttpContext.Request.UrlReferrer();
        //        string user_agent = HttpContext.Request.UserAgent();
        //        string user_cookies = HttpContext.Request.Cookies.ToJson();

        //        _context.eaforum_logs.Add(new Logs()
        //        {
        //            user_id = MEMBER_ID,
        //            user_ip = HttpContext.Connection.RemoteIpAddress.ToString(),
        //            page_url = page_url,
        //            referrer_url = referrer_url,
        //            user_agent = user_agent,
        //            user_cookies = user_cookies,
        //            app_type = 1,
        //            created_at = DateTime.Now,
        //            type_id = type,
        //            log_code = log_code,
        //            log_content = log_content
        //        });
        //        _context.SaveChanges();

        //    }
        //    catch (Exception ex)
        //    {
        //        log.Fatal(ex, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + " -> 添加操作日志");
        //    }

        //    return Json(new { code = 0, msg = "success" });
        //}
    }
}
